<?php

class Application_Model_SpecificationMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Specification');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Specification $spec){
		$data = array(
				'id_product'   => $spec->getId_product(),
				'spec_category' => $spec->getSpec_category(),
				'spec_name' => $spec->getSpec_name(),
				'spec_value' => $spec->getSpec_value(),
		);
	
		if (null === ($id = $spec->getId_spec())) {
			unset($data['id_spec']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_spec = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Specification $spec){
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$spec->setId_spec($row->id_spec)
			->setId_product($row->id_product)
			->setSpec_category($row->spec_category)
			->setSpec_name($row->spec_name)
			->setSpec_value($row->spec_value);
	}
	
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Specification();
			$entry->setId_spec($row->id_spec)
					->setId_product($row->id_product)
					->setSpec_category($row->spec_category)
					->setSpec_name($row->spec_name)
					->setSpec_value($row->spec_value);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function fetchAllFor($productId) {
		$specs = array();
		$resultSet = $this->getDbTable()
							->select()
							->where("id_product = ?", $productId)
							->order(array("spec_category","spec_name"))
							->query()->fetchAll(PDO::FETCH_ASSOC);
		
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Specification();
			$entry->setId_spec($row['id_spec'])
					->setId_product($row['id_product'])
					->setSpec_category($row['spec_category'])
					->setSpec_name($row['spec_name'])
					->setSpec_value($row['spec_value']);
			$specs[] = $entry;
		}
		return $specs;
	}
	
	public function delete($id){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id_spec = ?', $id);
		return $this->getDbTable()->delete($where);
	}
}

